import axios from 'axios';
import { debounce } from 'radash';
import { ref } from 'vue';

export const getUserList = (keyword: string) => axios.get('/api/common/users', { params: { keyword } });

const useUsers = () => {
  const users = ref([] as any[]);
  const loading = ref(false);
  const fetchUsers = debounce({ delay: 300 }, (value: string) => {
    try {
      if (!value) return;
      loading.value = true;
      users.value = [];
      getUserList(value).then(({ data }) => {
        users.value = (data.data || []).map((item: any) => ({
          label: item.nick_name,
          value: item.ad_account,
        }));
      });
    } catch (error) {
      //
    } finally {
      loading.value = false;
    }
  });

  return {
    users,
    loading,
    fetchUsers,
  };
};

export default useUsers;
